package ua.mk.chdu.rtem.diploma.core.agents.task.behaviours;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import ua.mk.chdu.rtem.diploma.core.model.global.AgentList;
import ua.mk.chdu.rtem.diploma.core.model.vo.TaskCompletionVO;
import ua.mk.chdu.rtem.diploma.core.model.vo.TaskContentVO;
import ua.mk.chdu.rtem.diploma.core.utils.MessageContentExtractor;

import java.io.IOException;

public class ProcessTaskBehaviour extends OneShotBehaviour {
    private Agent agent;
    private MessageContentExtractor<TaskContentVO> extractor = new MessageContentExtractor<TaskContentVO>();

    public ProcessTaskBehaviour(Agent a) {
        this.agent = a;
    }

    @Override
    public void action() {
        MessageTemplate messageTemplate =
                MessageTemplate.MatchSender(new AID(AgentList.getInstance().getScheduler(), AID.ISLOCALNAME));
        ACLMessage taskMessage = agent.blockingReceive(messageTemplate);
        TaskContentVO taskContent = extractor.extract(taskMessage);
        TaskCompletionVO resultVO = processTask(taskContent);
        ACLMessage taskResponse = buildResponseMessage(taskMessage, resultVO);
        agent.send(taskResponse);
    }

    private ACLMessage buildResponseMessage(ACLMessage task, TaskCompletionVO resultVO) {
        ACLMessage taskResponse = task.createReply();
        try {
            taskResponse.setContentObject(resultVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return taskResponse;
    }

    private TaskCompletionVO processTask(TaskContentVO task) {
        return new TaskCompletionVO(task.getValueObject() + " completed");
    }
}
